#ifndef SEARCHCONTROLLERTHREAD_H
#define SEARCHCONTROLLERTHREAD_H

#include <QThread>
#include <QWaitCondition>
#include <QMutex>

#include "SearchTask.h"
#include "ServiceConnector.h"

#include "Core/BoxApi/ApiManager.h"

#include <boost/utility.hpp>

class ISearchControllerThreadCallback;
class IConfig;

class SearchControllerThread  : public QThread
                              , private boost::noncopyable
{
Q_OBJECT
public  :

    SearchControllerThread(QObject *parent, IConfig *config,
                           ISearchControllerThreadCallback *callback);
    ~SearchControllerThread();

    /** Process next task
     *  @return
     *     true  - task is accepted
     *     false - thread is busy task rejected
     */
    bool pushTask(SearchTaskPtr task);

    /** Interrupt threas execution
        After this call thread will be stopped and current scna interrupted
     */
    void interrup();

private :

    /** inherited from QThread */
    void run();

    void processNextTask();

    enum TaskStatus
    {
        ServiceOutOfOrder,
        ServiceTimeout,
        TaskCompleted,
        TaskInterrupted,
    };

    /** Try handle scan requets on specified service */
    TaskStatus tryService(Core::BoxApi::IBoxConnectionPtr seviceConnector);

    SearchTaskPtr m_activeTask;

    QWaitCondition m_condition;
    QMutex m_mutex;

    /** Flag with atomic access signals that thread is busy
        0 - thread is free
        1 - thread is busy
     */
    QAtomicInt m_busyState;
    bool m_stopRequested;

    ISearchControllerThreadCallback * m_callback;

    /** Service slots configuration */
    IConfig *m_config;
    boost::shared_ptr<Core::EndUserAPI::ServiceConnector> m_service;

    std::auto_ptr<Core::BoxApi::ApiManager> m_boxManager;
};

#endif // SEARCHCONTROLLERTHREAD_H
